package com.tyut.config;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import jakarta.annotation.Resource;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.time.Duration;

@Configuration
public class BaseConfig {

    @Resource
    RedisConnectionFactory connectionFactory;

    @Bean
    MybatisPlusInterceptor getInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();   // 创建MybatisPlusInterceptor对象
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));   // 添加分页插件
        return interceptor;   // 返回MybatisPlusInterceptor对象
    }
    @Bean
    public PasswordEncoder encoder(){
        return new BCryptPasswordEncoder();   // 返回BCryptPasswordEncoder对象
    }

    @Bean(name = "GameUserRedis")
    public RedisTemplate<String,Object>  getRedisTemplate(){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new FastJsonRedisSerializer<Object>(Object.class));
        return redisTemplate;
    }

    @Bean
    public CacheManager getCacheManager () {
        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new FastJsonRedisSerializer<Object>(Object.class)))
                .entryTtl(Duration.ofDays(100));
        return new RedisCacheManager(
                RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory),
                configuration
        );
    }
}
